package serv_cmd

import (
	"sync"
	"time"

	"atomgit.com/openlinksaas/proto-gen-go.git/swarm_proxy_api"
	"atomgit.com/openlinksaas/swarm_api_proxy/config"
)

type SwarmProxyApiImpl struct {
	swarm_proxy_api.UnimplementedSwarmProxyApiServer
	cfg         *config.ProxyConfig
	logItemMap  sync.Map
	termItemMap sync.Map
}

func newSwarmProxyApiImpl(cfg *config.ProxyConfig) *SwarmProxyApiImpl {
	ret := &SwarmProxyApiImpl{cfg: cfg}
	go func() {
		time.Sleep(3 * time.Minute)
		ret.clearLogItem()
		// ret.clearTermItem()
	}()

	return ret
}

func (apiImpl *SwarmProxyApiImpl) clearLogItem() {
	cmpTime := time.Now().Unix() - 60
	removeItemList := []*LogItem{}
	apiImpl.logItemMap.Range(func(_, value any) bool {
		realValue := value.(*LogItem)
		if realValue.LastReadTime < cmpTime {
			removeItemList = append(removeItemList, realValue)
		}
		return true
	})
	for _, removeItem := range removeItemList {
		apiImpl.logItemMap.Delete(removeItem.LogId)
		removeItem.Cancel()
		close(removeItem.LogChan)
	}
}

func (apiImpl *SwarmProxyApiImpl) clearTermItem() {
	cmpTime := time.Now().Unix() - 60
	removeItemList := []*TermItem{}
	apiImpl.termItemMap.Range(func(_, value any) bool {
		realValue := value.(*TermItem)
		if realValue.LastReadTime < cmpTime {
			removeItemList = append(removeItemList, realValue)
		}
		return true
	})
	for _, removeItem := range removeItemList {
		apiImpl.termItemMap.Delete(removeItem.TermId)
		removeItem.Cancel()
		removeItem.Conn.Close()
		close(removeItem.OutChan)
	}
}
